/*
 * ProductAvailabilityAction.java
 *
 * Created on June 9, 2002, 9:11 AM
 */

package com.scalar.chiptrack.finance.actions;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.LabelValueBean;

import org.apache.poi.ss.usermodel.Workbook;

import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.commons.Constants;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.finance.dao.UpdateViewCostDAO;
import com.scalar.chiptrack.finance.dao.CostCodeSetupDAO;
import com.scalar.chiptrack.finance.dao.FinanceDataDumpReportDAO;
import com.scalar.chiptrack.finance.reports.forms.FinanaceReportForm;
import com.scalar.chiptrack.operations.process.ProcessTypes;
import com.scalar.chiptrack.operations.process.dao.FinishedGoodsDAO;
import com.scalar.chiptrack.operations.process.dao.PartNumber;
import com.scalar.chiptrack.operations.process.dao.ProductDao;
import com.scalar.chiptrack.operations.process.dao.NewProductDAO;
import com.scalar.chiptrack.operations.process.dao.gp.GPLotDAO;
import com.scalar.chiptrack.operations.vendor.Vendor;
import com.scalar.chiptrack.operations.vendor.dao.VendorDAO;
import com.scalar.chiptrack.operations.reports.DataDumpReportsHelper;
import com.scalar.chiptrack.sales.dao.CustomerDAO;
import com.scalar.chiptrack.sales.dao.NewCustomerDAO;
import com.scalar.chiptrack.sales.dao.SalesOrderDAO;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.utils.ConfigManager;
import com.scalar.chiptrack.utils.DateUtil;
import com.scalar.chiptrack.utils.ExcelUtils;
import com.scalar.chiptrack.utils.StringUtils;

/**
 * @author  Raj Vallamsetla
 * @version 1.0
 */
public class FinanceReportAction extends ChipTrackAction
{
    private static final String ACTION_NAME = "/financeReport.do";

    public ActionForward execute ( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response ) throws Exception
    {
        String action = request.getParameter( "action" );
        String processType = request.getParameter( "processType" );
        String baseProductId = request.getParameter( "baseproductID" );
        DBTransaction dbTransaction  = null;
        HashMap<String, String> info = new HashMap<String, String>();
        HashMap<String, String> errors = new HashMap<String, String>();
        HttpSession session = request.getSession ();
        FinanaceReportForm financeReportForm = (FinanaceReportForm)form;
        request.setAttribute( SessionKeys.INFO_MESSAGES, info );
        request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );
        ArrayList<LabelValueBean> mktgPartNumberdetailList = new ArrayList<LabelValueBean>();

        User user = ( User ) session.getAttribute ( SessionKeys.USER_KEY );
        if ( user == null )
        {
            session.setAttribute ( SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME + "?" + request.getQueryString () );
            return ( mapping.findForward ( "login" ) );
        }

        if( action.equals( "wip" ) )
        {
            ArrayList locationList = VendorDAO.getAllVendorLocations();
            request.setAttribute( "locationSelectList", locationList );
        }
        Workbook workbook = null;
        String fileName = "";

        request.setAttribute( "mktgPartNumberSelectList", FinishedGoodsDAO.loadAllFinishedGoods() );
                
        try
        {
            if ( action.equals("inventoryCost") || "updateCostTable".equalsIgnoreCase( action ) )
            {
                if ( "updateCostTable".equalsIgnoreCase( action ) )
                {
                    try
                    {
                        UpdateViewCostDAO.updateCostTable( null );
                        info.put ( "Inventory Costs updated successfully", null );
                    }
                    catch( Exception e )
                    {
                        errors.put ( "Could not update Inventory Costs", null );
                    }
                }

                PartNumber partNumber = null;
                int       baseProductIdInt  = 0;


                try
                {
                    baseProductIdInt = Integer.parseInt( baseProductId );
                }
                catch ( NumberFormatException nfe )
                {
                    baseProductIdInt = 0;
                }

                if( baseProductIdInt > 0 )
                {
                    ArrayList<PartNumber> partNumbersList = ProductDao.getPartNumberByBaseProductAndPsType( Constants.LOCATION_TYPE_FINISHED_GOODS , baseProductIdInt );
                    for( int i=0; i < partNumbersList.size(); i++ )
                    {
                        partNumber = ( PartNumber ) partNumbersList.get( i );
                        mktgPartNumberdetailList.add( new org.apache.struts.util.LabelValueBean( partNumber.getPartNumber(), partNumber.getProcessStepId() ) );
                    }
                }

                request.setAttribute( "mktgPartNumberdetailList", mktgPartNumberdetailList );
                request.setAttribute( "baseProductsList", ProductDao.loadAllBaseProducts( null ) );

                return( mapping.findForward( "inventoryCost" ) );
            }
            
        }
        catch( Exception e )
        {
            e.printStackTrace();
        }

        if( action.equals( "sortdetails" ) )
        {
            try
            {   ArrayList <PartNumber> partNumberList = ProductDao.getPartNumber(Constants.LOCATION_TYPE_SORT);

                for( int i = 0; i < partNumberList.size(); i++ )
                {
                    PartNumber partNumber = ( PartNumber ) partNumberList.get(i);
                    mktgPartNumberdetailList.add ( new LabelValueBean( partNumber.getPartNumber(), partNumber.getProcessStepId() ) );
                }

                request.setAttribute( "productList", mktgPartNumberdetailList );
                request.setAttribute( "years", 		 SalesOrderDAO.getYearList() );
                request.setAttribute( "quarterList", loadQuarters() );
                request.setAttribute( "currentQtr",  getCurrentQuarter() );
            }
            catch( Exception e )
            {
                e.printStackTrace();
            }
            return( mapping.findForward( "sortdetails" ) );

        }

        if( action.equals( "revenue" ) )
        {
            // Added by Prabhanjan (26 mar 2004) to retreive list of years to display in revenue report screen.
            ArrayList customerList = CustomerDAO.getAllCustomers();
            request.setAttribute( "customerSelectList", customerList );
            request.setAttribute ( "years", SalesOrderDAO.getYearList () );

            //Prabhanjan, Jul 24, 2004
            //request.setAttribute( "salesRepList", CustomerDAO.loadAllSalesReps() );
            request.setAttribute( "salesRepList", SalesOrderDAO.getSalesPersons() );
            //request.setAttribute( "endUserList", EndUserDAO.loadAllEndUsers() );
            request.setAttribute( "endUserList", NewCustomerDAO.loadAllOdms() );

            // Prabhanjan, Jul 28, 2004
            request.setAttribute( "quarterList", loadQuarterList() );
            request.setAttribute( "currentQtr", getCurrentQuarter() );

            return( mapping.findForward( "revenueReport" ) );
        }

        if( action.equals( "revenueByEndCustomer" ) )
        {
            request.setAttribute ( "years", SalesOrderDAO.getYearList () );
            request.setAttribute( "endUserList", NewCustomerDAO.loadAllOdms() );
            request.setAttribute( "quarterList", loadQuarters() );
            request.setAttribute( "currentQtr", getCurrentQuarter() );
            ArrayList baseProductList = ProductDao.loadAllBaseProducts( null );
            request.setAttribute( "baseProductList", baseProductList );

            return( mapping.findForward( "revenueReportByEndCustomer" ) );
        }

        // Prabhanjan, Sep 12, 2004
        if( "vertical".equals( action ) )
        {
            request.setAttribute( "years", SalesOrderDAO.getYearList() );
            request.setAttribute( "quarterList", loadQuarterList() );
            request.setAttribute( "currentQtr", getCurrentQuarter() );
            return ( mapping.findForward( "verticalReport" ) );
        }

        if( action.equals( "inventory" ) )
            return( mapping.findForward( "inventoryCostReport" ) );

        if( action.equals( "wip" ) )
            return( mapping.findForward( "wipCostReport" ) );

        if( action.equals( "product" ) )
        {
            if( Constants.FINANCE_INTEGRATION_TYPE_GREAT_PLAINS.equalsIgnoreCase( ConfigManager.getFinanceIntegrationType() ) )
            {
                try
                {
                    GPLotDAO.updateLostCostInformationFromGP();
                }
                catch( Exception e )
                {
                    System.out.println( "Could update the Lot Cost Information" );
                    e.printStackTrace();
                }
            }
            return( mapping.findForward( "productCostReport" ) );
        }
        if( action.equals( "yieldCostVarienceReport" ) )
        {
            if( financeReportForm.getProcessType() == null || "0".equalsIgnoreCase ( financeReportForm.getProcessType() ) )
            {
               request.setAttribute( "partNumberList", new ArrayList() );
            }
            else
            {
                if ( financeReportForm.getBaseProductId() > 0  )
                {
                    request.setAttribute( "partNumberList", NewProductDAO.loadPartNumbers( null, 0, financeReportForm.getProcessType(), true, true, true, financeReportForm.getBaseProductId() ) );
                }
                else
                {
                    request.setAttribute( "partNumberList", NewProductDAO.loadPartNumbers( null, 0, financeReportForm.getProcessType(), true, true, true, 0 ) );
                }
            }

            request.setAttribute( "vendorList", VendorDAO.getVendorNamesByProcessByUserType (null,"all",null) );
            request.setAttribute( "processList",  loadProcess() );
            request.setAttribute( "baseproductList", NewProductDAO.loadAllBaseProducts( null, true, true ) );

            return( mapping.findForward( "yieldCostVarienceReport" ) );
        }
        if( action.equals( "yieldCostVarienceReportExcel" ) )
        {
            ArrayList reportList = FinanceDataDumpReportDAO.getYieldCostVarienceReport ( null, financeReportForm );

            workbook =  DataDumpReportsHelper.getWorkbook( reportList, "Yield Cost Variance Report", null,null,null );
            
            fileName = "Yield Cost Variance Report-" + DateUtil.getTimeStamp() ;

            //To GENERATE THE EXCEL REPORT
            ExcelUtils.generateExcelReport( workbook, fileName, response );

            return( mapping.findForward( "yieldCostVarienceReport" ) );
        }

        if ( action.equalsIgnoreCase ( "ProjectionLots" ) )
        {
            try
            {
                ArrayList<LabelValueBean> processList = new ArrayList<LabelValueBean>();
                ArrayList vendorList            = null;

                processList.add( new LabelValueBean( ProcessTypes.fab , ProcessTypes.fab ) );
                processList.add( new LabelValueBean( ProcessTypes.sort , ProcessTypes.sort ) );
                processList.add( new LabelValueBean( ProcessTypes.assembly, ProcessTypes.assembly ) );
                processList.add( new LabelValueBean( ProcessTypes.test , ProcessTypes.test ) );

                if( processType == null || "0".equalsIgnoreCase ( processType ) )
                {
                    mktgPartNumberdetailList = new ArrayList<LabelValueBean>();
                    vendorList = new ArrayList();
                }
                else
                {
                    vendorList = new ArrayList();
                    ArrayList<PartNumber> partNumberList = ProductDao.getPartNumber( processType );
                    mktgPartNumberdetailList = new ArrayList();
                    for( int i = 0; i < partNumberList.size(); i++ )
                    {
                        PartNumber partNumber = ( PartNumber ) partNumberList.get(i);
                        mktgPartNumberdetailList.add ( new LabelValueBean( partNumber.getPartNumber(), partNumber.getProcessStepId() ) );
                    }
                    ArrayList<Vendor> vendorTempList = VendorDAO.getAllVendors();
                    for(int i=0; i <  vendorTempList.size() ; i++ )
                    {
                       Vendor vendor =  ( Vendor ) vendorTempList.get ( i );
                       vendorList.add( new LabelValueBean ( vendor.getVendorName() , vendor.getVendorId()+"" ) );
                    }
                }
                request.setAttribute ( "vendorList" ,  vendorList );
                request.setAttribute ( "processList",  processList );
                request.setAttribute ( "productList",  mktgPartNumberdetailList );
            }
            catch( Exception e )
            {
                e.printStackTrace();
            }
            return( mapping.findForward( "ProjectionLots" ) );
        }

        if( action.equals( "overHead" ) )
            return( mapping.findForward( "overHead" ) );

        if( action.equals( "vendor" ) )
            return( mapping.findForward( "vendor" ) ) ;

        if( action.equals( "inventoryInfo" ) )
            return( mapping.findForward( "inventoryInfo" ) ) ;

        // Balaram, Jun 22, 2004
        if( action.equals( "costReports" ) )
        {
            if( Constants.FINANCE_INTEGRATION_TYPE_GREAT_PLAINS.equalsIgnoreCase( ConfigManager.getFinanceIntegrationType() ) )
            {
                try
                {
                    GPLotDAO.updateLostCostInformationFromGP();
                }
                catch( Exception e )
                {
                    System.out.println( "Could update the Lot Cost Information" );
                    e.printStackTrace();
                }
            }

            return( mapping.findForward( "costReports" ) );
        }

        if( action.equals( "costVariance" ) )
        {
            try
            {
                ArrayList updateTimeList = CostCodeSetupDAO.loadCostCodeUpdateTime( dbTransaction );
                if ( updateTimeList != null && updateTimeList.size() > 1 )
                {
                    financeReportForm.setCostCostUpdateTime1( ( (LabelValueBean)updateTimeList.get(0) ).getValue() );
                    financeReportForm.setCostCostUpdateTime2( ( (LabelValueBean)updateTimeList.get(1) ).getValue() );
                }    
                request.setAttribute ( "updateTimeList" ,  updateTimeList );
            }
            catch( Exception e )
            {
                System.out.println( "Could not load the previous schedule times" );
                e.printStackTrace();
            }

            return( mapping.findForward( "costVariance" ) );
        }
        if("costVarianceNew".equalsIgnoreCase(action)){

            request.setAttribute( "years", 		 SalesOrderDAO.getYearList() );
            request.setAttribute( "quarterList", loadQuarters() );

            int currQtr = DateUtil.getCurrentQtrNo();
            int currYear = DateUtil.getCurrentYear();
            financeReportForm.setFromQtr(currQtr==1 ? 4 : currQtr-1);
            financeReportForm.setFromYear(currQtr==1 ? currYear-1 : currYear);

            financeReportForm.setToQtr(currQtr);
            financeReportForm.setToYear(currYear);
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.DATE, -1);

            financeReportForm.setFromDate(StringUtils.formatDateToString(cal.getTime()));//AsOfDate
            return( mapping.findForward( "costVarianceNew" ) );
        }
        if("xlsCostVarianceNew".equalsIgnoreCase(action))
        {
            ArrayList<ArrayList> reportList = FinanceDataDumpReportDAO.getStdCostVarianceReport (null, financeReportForm );

            workbook =  DataDumpReportsHelper.getWorkbook( reportList, "Inventory Cost Variance Report", null, null,null );

            fileName = "Cost Variance Report-" + DateUtil.getTimeStamp() ;

            //To GENERATE THE EXCEL REPORT
            ExcelUtils.generateExcelReport( workbook, fileName, response );

            return( mapping.findForward( "costVarianceNew" ) );
        }

        if( action.equals( "stdYieldedUnitCost" ) )
            return( mapping.findForward( "stdYieldedUnitCost" ));

        if( action.equals( "vendorYieldedUnitCost" ) )
            return( mapping.findForward( "vendorYieldedUnitCost" ));

        if( action.equals( "stdVsVendorUnitAndYieldedCost" ) )
            return( mapping.findForward( "stdVsVendorUnitAndYieldedCost" ));

        if( action.equals( "allStagesStdVendorUnitYieldedCost" ) )
            return( mapping.findForward( "allStagesStdVendorUnitYieldedCost" ));

        if( action.equals( "stdYieldedCostPercentage" ) )
            return( mapping.findForward( "stdYieldedCostPercentage" ));

        if( action.equals( "vendorYieldedCostPercentage" ) )
            return( mapping.findForward( "vendorYieldedCostPercentage" ));

        if( action.equals( "stdVsVendorYieldedCost" ) )
            return( mapping.findForward( "stdVsVendorYieldedCost" ));

        if( action.equals( "stdCostVsYieldedCost" ) )
            return( mapping.findForward( "stdCostVsYieldedCost" ));

        if( action.equals( "vendorCostVsYieldedCost" ) )
            return( mapping.findForward( "vendorCostVsYieldedCost" ));

        else
            return null;
    }

    public ArrayList loadQuarterList()
    {
        int start_qtr = 1;
        int end_qtr = 4;

        ArrayList yearList = new ArrayList ();
        for ( int year = start_qtr; year <= end_qtr; year++ )
        {
            yearList.add ( new LabelValueBean ( "Qtr " + year, year + "") );
        }
        yearList.add( new LabelValueBean ( "All", "All") );

        return yearList;
    }
    public ArrayList loadProcess()
    {
        ArrayList processList = new ArrayList();

        processList.add( new LabelValueBean( "All Process", "0" ) );
        processList.add( new LabelValueBean( "ASSEMBLY", "Assembly" ) );
        processList.add( new LabelValueBean( "FT", "FT" ) );
        
        return processList;
    }
    public ArrayList loadQuarters()
    {
        int start_qtr = 1;
        int end_qtr = 4;

        ArrayList yearList = new ArrayList ();
        for ( int year = start_qtr; year <= end_qtr; year++ )
        {
            yearList.add ( new LabelValueBean ( "Qtr " + year, year + "") );
        }

        return yearList;
    }

    // Prabhanjan, Jul 28, 2004 to generate quarter list
    private String getCurrentQuarter()
    {
        String qtr = "1";
        Calendar c = Calendar.getInstance();
        int month = c.get( Calendar.MONTH );

        if( month > 8 )
        {
            qtr = "4";
        }
        else if( month > 5 )
        {
            qtr = "3";
        }
        else if( month > 2 )
        {
            qtr = "2";
        }
        else
        {
            qtr = "1";
        }

        return qtr;
    }
}
